package com.jy.api.service.impl;

import com.jy.api.dao.KitchenPrintConfigDao;
import com.jy.api.domain.KitchenPrintConfig;
import com.jy.api.exception.MyException;
import com.jy.api.service.KitchenPrintService;
import com.jy.api.signUpReq.admin.KitchenPrintSignUpReq;
import com.jy.api.util.UuidUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by lihu on 2017/11/14.
 */
@Service
public class KitchenPrintServiceImpl implements KitchenPrintService {

    @Autowired
    KitchenPrintConfigDao kitchenPrintConfigDao;

    @Override
    @Transactional
    public void saveOrUpdate(KitchenPrintSignUpReq kitchenPrintSignUpReq) {
        KitchenPrintConfig kitchenPrintConfig;
        if (StringUtils.isNoneBlank(kitchenPrintSignUpReq.getId())) {
            kitchenPrintConfig = kitchenPrintConfigDao.findOne(kitchenPrintSignUpReq.getId());
            if (kitchenPrintConfig == null) {
                throw new MyException("参数信息有误！");
            }
            kitchenPrintConfig.setIp(kitchenPrintSignUpReq.getIp());
            kitchenPrintConfig.setEnabled(kitchenPrintSignUpReq.isEnabled());
            kitchenPrintConfig.setPort(kitchenPrintSignUpReq.getPort());

        } else {
            kitchenPrintConfig = new KitchenPrintConfig();
            BeanUtils.copyProperties(kitchenPrintSignUpReq, kitchenPrintConfig);
            kitchenPrintConfig.setId(UuidUtil.getUuid());

        }
        // check(kitchenPrintConfig);
        kitchenPrintConfigDao.save(kitchenPrintConfig);
    }

    @Override
    public List<KitchenPrintConfig> getKitchenPrintConfig(String storeId) {
        return kitchenPrintConfigDao.findListByStoreIdAndEnabled(storeId, true);
    }

    /**
     * 端口校验
     *
     * @return
     */
    private void check(KitchenPrintConfig kitchenPrintConfig) {
        List<KitchenPrintConfig> configs = kitchenPrintConfigDao.findListByStoreIdAndEnabled(
                kitchenPrintConfig.getStoreId(), true);
        for (KitchenPrintConfig config : configs) {
            if (config.getPort() == kitchenPrintConfig.getPort() &&
                    !StringUtils.equals(config.getId(), kitchenPrintConfig.getId())) {
                throw new MyException("端口号重复！请重新设置！");
            }

            if (StringUtils.equals(config.getIp(), kitchenPrintConfig.getIp())
                    && !StringUtils.equals(config.getId(), kitchenPrintConfig.getId())) {
                throw new MyException("ip重复！请重新设置！");
            }
        }
    }
}
